package com.davidlife.javaee.xml.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.Selector;

import java.io.File;
import java.io.IOException;

/*
* 快捷查询方式：
		1. selector:选择器
			* 使用的方法：`Elements	select(String cssQuery)`
				* 语法：参考`org.jsoup.select.Selector`类中定义的语法(Jsoup javadoc中),同CSS选择器（或JQuery选择器）都很类似
				* 如：`el.select("#username_id")`，`el.select("student[number='heima_0001'] > name")`
 */
public class XmlJsoupSelectorDemo {
    public static void main(String[] args) throws IOException {
        //2.1获取student.xml的path
        String path = XmlJsoupDemo.class.getClassLoader().getResource("student.xml").getPath();
        //2.2解析xml文档，加载文档进内存，获取dom树--->Document
        Document document = Jsoup.parse(new File(path), "utf-8");

        //直接用标签名select
        Elements ele_name = document.select("name");
        System.out.println(ele_name);

        System.out.println("-----------------------");

        //选择所有带有number属性，且number属性值以"heima_"开头的所有student元素的所有直接name子标签
        Elements ele_heima_name = document.select("student[number^=heima_] name");
        System.out.println(ele_heima_name);

        System.out.println("-----------------------");

        //也可采用链式编程
        Element name = document.select("student[number=chuanzhi_0001]").get(0).select("name").get(0);
        System.out.println(name);

        System.out.println("-----------------------");

        //也可直接用org.jsoup.select.Selector的静态方法进行查询
        Elements ele_heima_name2 = Selector.select("student[number^=heima_] name", document);
        System.out.println(ele_heima_name2);
    }
}
